/*
 * ShowDownloadFile.java
 *
 * Created on __DATE__, __TIME__
 */

package Windows.DownLoads;

import java.awt.Desktop;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import Client.ClientListener;
import Client.MsgEvent;
import GroupWare.DownloadTask;
import GroupWare.DownloadTaskListener;
import GroupWare.Pip;
import Tools.IMG;
import Tools.InfoFormat;
import Tools.JLabelStyle;
import Tools.Log;
import Tools.Units;
import Windows.MainWindows;
import Windows.PicPanel;

/**
 * 
 * @author __USER__
 */
public class ShowDownloadTaskPanel extends PicPanel implements MouseListener, ClientListener, DownloadTaskListener {
	private static ImageIcon iiStart;
	private static ImageIcon iiStart2;
	private static ImageIcon iiStop;
	private static ImageIcon iiStop2;
	public final DownloadTask df;
	private ShowDownloadPanel sdp;

	// GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JLabel jLabel1;

	private javax.swing.JLabel jLabel10;

	// GEN-END:initComponents

	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JLabel jLabel7;
	private javax.swing.JProgressBar jProgressBar1;
	private javax.swing.JLabel jlAtt;
	private javax.swing.JLabel jlClose;
	private javax.swing.JLabel jlConment;
	private javax.swing.JLabel jlIco;
	private javax.swing.JLabel jlNone;
	private javax.swing.JLabel jlRemnantTime;
	private javax.swing.JLabel jlResPip;
	private javax.swing.JLabel jlSize;
	private javax.swing.JLabel jlSpeed;
	private javax.swing.JLabel jlStart;
	private javax.swing.JLabel jlTile;
	private static ImageIcon iiClose;
	private static ImageIcon iiClose2;

	// End of variables declaration//GEN-END:variables

	public ShowDownloadTaskPanel(final DownloadTask df) {
		super(IMG.DownTaskbg, IMG.DownTaskbg2);
		this.df = df;
		this.df.addListener(this);

		initComponents();

		try {
			if (iiStart == null) {
				File f = new File("Skin/taskstate.png");
				iiClose = new ImageIcon(ImageIO.read(f).getSubimage(28, 0, 14, 11));
				iiClose2 = new ImageIcon(ImageIO.read(f).getSubimage(42, 0, 14, 11));
				f = new File("Skin/play.png");
				iiStart = new ImageIcon(ImageIO.read(f).getSubimage(0, 0, 32, 37));
				iiStart2 = new ImageIcon(ImageIO.read(f).getSubimage(32, 0, 32, 37));
				f = new File("Skin/stop.png");
				iiStop = new ImageIcon(ImageIO.read(f).getSubimage(0, 0, 32, 37));
				iiStop2 = new ImageIcon(ImageIO.read(f).getSubimage(32, 0, 32, 37));
			}
		} catch (IOException e) {
		}

		jlTile.setText(df.getXML().get("name"));// 文件名，即任务标题

		jlPicStyle(jlIco, true);
		jlPicStyle(jlAtt, true);
		jlPicStyle(jlConment, true);
		jlPicStyle(jlResPip, true);
		jlPicStyle(jlStart, true);
		jlPicStyle(jlClose, true);

		jlStart.setSize(45, 37);

		jlIco.addMouseListener(this);
		jlTile.addMouseListener(this);
		jlConment.addMouseListener(this);
		jlAtt.addMouseListener(this);
		jlResPip.addMouseListener(this);
		jlStart.addMouseListener(this);
		jlClose.addMouseListener(this);

		MouseListener ml = JLabelStyle.getStyleListener();

		jlIco.addMouseListener(ml);
		jlTile.addMouseListener(ml);
		jlConment.addMouseListener(ml);
		jlAtt.addMouseListener(ml);
		jlResPip.addMouseListener(ml);
		jlStart.addMouseListener(ml);
		jlClose.addMouseListener(ml);

		JLabelStyle.setStyle(jlIco);
		JLabelStyle.setStyle(jlTile, true);
		JLabelStyle.setStyle(jlConment);
		JLabelStyle.setStyle(jlAtt);
		JLabelStyle.setStyle(jlResPip);
		JLabelStyle.setStyle(jlStart);
		JLabelStyle.setStyle(jlClose);
		JLabelStyle.setStyle(jLabel1);
		JLabelStyle.setStyle(jLabel3);
		JLabelStyle.setStyle(jLabel5);
		JLabelStyle.setStyle(jLabel7);
		JLabelStyle.setStyle(jLabel10);
		JLabelStyle.setStyle(jlNone);
		JLabelStyle.setStyle(jlRemnantTime);
		this.addMouseListener(this);

		jProgressBar1.setStringPainted(true);

		if(df.isOK()){
			UPDATE(DownloadTask.EVENT_ORVER);
		}else{
			UPDATE(DownloadTask.EVENT_PAUSE);
		}
	}

	@Override
	public void achieveEvent(DownloadTask dt) {
		// ////////////////////////////////////
		Log.print("任务完成:" + dt);
		dt.getXML().put("State", "OK");
		new ShowDownloadWindow(dt).start();// 滑出提示窗口
		UPDATE(DownloadTask.EVENT_ORVER);
		// /////////////////////////////////////
		for (int i = 0; i < dt.getWaitingPips().size(); i++) {
			MainWindows.getInstance().client.send("<ResContribute userid=\"" + dt.getWaitingPips().get(i).getUserID() + "\" />");// 更新贡献者积分
		}
		dt.getSharePath().add(dt);// 加入共享目录中去
	}

	public DownloadTask getDf() {
		return df;
	}

	public String getMd5() {
		return df.md5;
	}

	public ShowDownloadPanel getSdp() {
		return sdp;
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jProgressBar1 = new javax.swing.JProgressBar();
		jlTile = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();
		jlNone = new javax.swing.JLabel();
		jLabel5 = new javax.swing.JLabel();
		jlSpeed = new javax.swing.JLabel();
		jLabel7 = new javax.swing.JLabel();
		jlRemnantTime = new javax.swing.JLabel();
		jlResPip = new javax.swing.JLabel();
		jLabel10 = new javax.swing.JLabel();
		jlClose = new javax.swing.JLabel();
		jlStart = new javax.swing.JLabel();
		jlConment = new javax.swing.JLabel();
		jlAtt = new javax.swing.JLabel();
		jLabel1 = new javax.swing.JLabel();
		jlSize = new javax.swing.JLabel();
		jlIco = new javax.swing.JLabel();

		jlTile.setFont(new java.awt.Font("宋体", 1, 12));

		jLabel3.setText("\u5df2\u7ecf\u5b8c\u6210:");

		jlNone.setText("1024MB(90%)");

		jLabel5.setText("\u4e0b\u8f7d\u901f\u5ea6:");

		jlSpeed.setText("1024MB/s");

		jLabel7.setText("\u5269\u4f59\u65f6\u95f4:");

		jlRemnantTime.setText("24\u65f660\u520660\u79d2");

		jlResPip.setText("256/1024");

		jLabel10.setText("种子:");

		jlClose.setText("x");
		jlClose.setToolTipText("\u5220\u9664\u4efb\u52a1");

		jlStart.setBackground(new java.awt.Color(51, 102, 255));
		jlStart.setText("||");
		jlStart.setToolTipText("\u542f\u52a8/\u505c\u6b62");

		jlConment.setText(">>");
		jlConment.setToolTipText("\u53d1\u8868\u8bc4\u8bba");

		jlAtt.setText("AT");
		jlAtt.setToolTipText("资源属性");

		jLabel1.setText("\u6587\u4ef6\u5927\u5c0f:");

		jlSize.setText("1024MB");

		org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
		this.setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
				layout.createSequentialGroup()
						.addContainerGap()
						.add(jlIco, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 73, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
						.add(layout
								.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
								.add(layout.createSequentialGroup().add(jlTile, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 499, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
								.add(layout.createSequentialGroup().add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jLabel3).add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jlSize, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE).add(jlNone)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel5).add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel7)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
										.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jlRemnantTime).add(layout.createSequentialGroup().add(jlSpeed).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 118, Short.MAX_VALUE).add(jLabel10).add(6, 6, 6))).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(jlResPip, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 79, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)).add(layout.createSequentialGroup().add(jProgressBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 501, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)))
						.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING).add(jlStart, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 37, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false).add(org.jdesktop.layout.GroupLayout.TRAILING, jlAtt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(org.jdesktop.layout.GroupLayout.TRAILING, jlConment, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(org.jdesktop.layout.GroupLayout.TRAILING, jlClose, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
						.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
				.add(org.jdesktop.layout.GroupLayout.TRAILING,
						layout.createSequentialGroup().addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(jlClose).add(jlTile)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
								.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jlStart, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 36, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(layout.createSequentialGroup().add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(jLabel1).add(jlRemnantTime).add(jLabel7).add(jlSize)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(jLabel3).add(jlResPip).add(jLabel10).add(jlSpeed).add(jLabel5).add(jlNone)))).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
								.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(layout.createSequentialGroup().add(jlAtt).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(jlConment)).add(jProgressBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))).add(layout.createSequentialGroup().addContainerGap().add(jlIco, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 79, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addContainerGap(20, Short.MAX_VALUE)));
	}// </editor-fold>

	/**
	 * 标签事件处理
	 */
	public void jlClickedEvent(JLabel jl) {
		if (jl.equals(jlTile)) {
			// --资源文件名标签
			// System.out.println("资源名称：被单击弹出详细信息窗口！");
			if (df.getF().exists()) {
				try {
					Desktop.getDesktop().open(df.getF());
					Log.print("打开文件:" + df.getF().toString());
				} catch (IOException e) {
					JOptionPane.showMessageDialog(this, "打开文件异常，" + e.getMessage(), "打开文件", JOptionPane.OK_OPTION, IMG.MESSAGE_ICON2);
				}
			} if(df.getTmpfile().exists()){
				JOptionPane.showMessageDialog(this, "文件未下载完成！", "打开文件", JOptionPane.OK_OPTION, IMG.MESSAGE_ICON2);
			}else {
//				JOptionPane.showMessageDialog(this, "文件不存在！", "打开文件", JOptionPane.OK_OPTION, IMG.MESSAGE_ICON2);
			}
		} else if (jl.equals(jlAtt)) {
			// --查看资源信息标签
			System.out.println("资源属性：被单击！");
			MainWindows.getResInfo().display(this.df.getXML());
		} else if (jl.equals(jlConment)) {
			// --查看资源评论标签
			System.out.println("资源评论：被单击！");
		} else if (jl.equals(jlStart)) {
			// --启动/停止标签

		} else if (jl.equals(jlResPip)) {
			// --查看资源来源信息标签
			System.out.println("资源来源：被单击！");
		} else if (jl.equals(jlIco)) {
			System.out.println("资源图标：被单击！" + jl.getText());

			try {
				Desktop.getDesktop().open(df.getF().getParentFile());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 标签图片
	 * 
	 * @param jl
	 * @param b
	 *            状态 true 表示按下
	 */
	public void jlPicStyle(JLabel jl, boolean b) {

		if (jl == jlAtt) {
			// --查看资源信息标签
			jl.setText("");
			jl.setIcon(b ? IMG.iiAtt : IMG.iiAtt2);
		} else if (jl == jlConment) {
			// --查看资源评论标签
			jl.setText("");
			jl.setIcon(b ? IMG.iiConment : IMG.iiConment2);
		} else if (jl == jlStart) {
			// --启动/停止标签
			jl.setText("");
			jl.setIcon(df.isDoing() ? (b ? iiStop : iiStop2) : (b ? iiStart : iiStart2));
		} else if (jl == jlClose) {
			jl.setText("");
			jl.setIcon(b ? iiClose : iiClose2);
		} else if (jl == jlIco) {
			jl.setText("");
			jl.setIcon(df.getTmpfile().exists()||df.getF().exists() ? (df.isDoing() ? b : !b) ? IMG.iiIco : IMG.iiIco2 : IMG.noICO);
		}
	}
	// --鼠标单击标签
	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		Object obj = e.getSource();
		if (obj.getClass() == JLabel.class)
			jlClickedEvent((JLabel) obj);// 标签被单击事件处理
	}

	// --鼠标进入事件处理
	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		Object obj = e.getSource();
		if (obj.getClass() == JLabel.class) {
			JLabel jl = (JLabel) obj;
			// JLabelStyle.jlStyle(jl, JLabelStyle.MOUSE_ENTERED);
			jlPicStyle(jl, false);
		}
		this.actionEvent(true);
		sdp.setK(sdp.getAldf().indexOf(this));

	}

	// --鼠标离开事件
	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		Object obj = e.getSource();
		if (obj.getClass() == JLabel.class) {
			JLabel jl = (JLabel) obj;
			// JLabelStyle.jlStyle(jl, JLabelStyle.MOUSE_EXITED);
			jlPicStyle(jl, true);
		}
		this.actionEvent(false);
		sdp.setK(-1);
	}

	/**
	 * 鼠标按压事件
	 */
	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		Object obj = e.getSource();
		if (obj.getClass() == JLabel.class) {
			JLabel jl = (JLabel) obj;
			// JLabelStyle.jlStyle(jl, JLabelStyle.MOUSE_PRESSED);
			jlPicStyle(jl, true);
			if (jl == jlStart) {
				if (!df.getTmpfile().exists()&&!df.getF().exists()) {
					int k = JOptionPane.showConfirmDialog(null, "资源被移除，您确认重新下载吗？");
					if (k == 0) {
						df.reset();
					}
				}
				if (!df.isDoing() && !df.isOK())
					df.start();
				else
					df.pause();

			} else if (jl == jlClose) {
				sdp.removeTask(this);
			}
		}
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		Object obj = e.getSource();
		if (obj.getClass() == JLabel.class) {
			JLabel jl = (JLabel) obj;
			// JLabelStyle.jlStyle(jl, JLabelStyle.MOUSE_ENTERED);
			jlPicStyle(jl, false);
		}
	}

	@Override
	public void onCloseEvent(Client.CloseEvent cce) {
	}

	@Override
	public void onMsgEvent(MsgEvent ce) {
		// ---索取文件请求返回结果,得到种子
		if (ce.getCmd().FLAG.equalsIgnoreCase("pip")) {
			Log.print("[Download]发现种子:" + ce.getCmd());
			try {
				String md5 = ce.getCmd().get("md5");
				if (md5.equalsIgnoreCase(df.md5)) {// 过滤文件种子
					long gcode = Long.parseLong(ce.getCmd().get("tgcode"));
					long gucode = Long.parseLong(ce.getCmd().get("tgucode"));
					String userid = ce.getCmd().get("userid");
					String address = ce.getCmd().get("address");
					String strsport = ce.getCmd().get("sport");
					InetAddress ia = null;
					int sport = 0;
					if (address != null && strsport != null) {
						address = address.startsWith("/") ? address.substring(1, address.length()) : address;
						ia = InetAddress.getByName(address);
						sport = Integer.parseInt(strsport);
					}
					df.addSeed(new Pip(gcode, gucode, userid, ia, sport));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void PauseEvent(DownloadTask dt) {
		df.getSaveXML();
		UPDATE(DownloadTask.EVENT_PAUSE);
	}

	@Override
	public void periodsEvent(DownloadTask dt) {
		if (df.isDoing()) {
			df.getSaveXML();
			UPDATE(DownloadTask.EVENT_PERIODS);
		}
	}

	public void setSdp(ShowDownloadPanel sdp) {
		this.sdp = sdp;
	}

	@Override
	public void TaskExceptionEvent(DownloadTask dt) {
//		df.pause(false);//不触发事件
		UPDATE(DownloadTask.EVENT_EXCEPTION);
	}

	/**
	 * 多线程反馈主线程刷新UI界面
	 * 
	 * @param state
	 *            状态
	 */
	private synchronized void UPDATE(int state) {
		switch (state) {
		case DownloadTask.EVENT_PAUSE:
			this.jlTile.setText("[暂停] " + df.getF().getName());
			this.treeNode.setImageIcon(IMG.TASK_PAUSE); // 暂停
			break;
		case DownloadTask.EVENT_ORVER:
			this.jlTile.setText("[完成] " + df.getF().getName());
			this.treeNode.setImageIcon(IMG.TASK_ORVER); // 完成
			break;
		case DownloadTask.EVENT_PERIODS:
			this.jlTile.setText("[运行] " + df.getF().getName());
			this.treeNode.setImageIcon(IMG.TASK_PERIODS); // 运行时
			break;
		case DownloadTask.EVENT_EXCEPTION:
			this.jlTile.setText("[异常] " + df.getF().getName());
			this.treeNode.setImageIcon(IMG.TASK_EXCEPTION); // 异常
		}
		long time = df.getRemnantTime();// 秒
		final String timstr = InfoFormat.formatTimeGB(time);
		final String size = Units.byteCondense(df.length);
		final String none = Units.byteCondense(df.getAchieve());
		long sped = df.getAvgSpeed();

		// 显示下载速度：完成任务将显示平均速度，否则显示当前速度
		final String speed = Units.byteCondense((state == DownloadTask.EVENT_ORVER) ? df.getSpeed() : sped) + "/s";//
		final int prog = df.getCourse();
//		Log.print(df.md5+" prog  "+prog);
		final String pip = df.getTaskSum() + "/" + (df.getTaskSum() + df.getWaitSum());
		this.treeNode.setUserObject(InfoFormat.shortString(df.getF().getName(), 10) + "(" + (time > 0 ? (prog + "%") : "完成") + ") " + (time > 0 ? timstr : ""));

		java.awt.EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				if (df.getTmpfile().exists()||df.getF().exists()) {
					jlSize.setText(size);
					jlNone.setText(none);
					jProgressBar1.setValue(prog);
					jlRemnantTime.setText(timstr);
					jlSpeed.setText(speed);
					jlResPip.setText(pip);
					jlPicStyle(jlStart, true);
					jlPicStyle(jlIco, true);

				} else {
					jlTile.setText("[已删除]" + df.getF().getName());
					jlSize.setText("");
					jlNone.setText("");
					jProgressBar1.setValue(0);
					jlRemnantTime.setText("");
					jlSpeed.setText("");
					jlResPip.setText("");
					jlPicStyle(jlStart, true);
					jlPicStyle(jlIco, true);
					ShowDownloadTaskPanel.this.treeNode.setImageIcon(IMG.TASK_ERROR);
				}
				MainWindows.Tree.jTree.updateUI();
			}
		});
	}

}
